package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constant.KillConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseDoc;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.domain.KillCourse;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import cn.itsource.ymcc.openfeign.EsCourseOpenFeign;
import cn.itsource.ymcc.openfeign.KillOpenFeign;
import cn.itsource.ymcc.producer.OrderProducer;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICourseOrderItemService;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.util.CodeGenerateUtils;
import cn.itsource.ymcc.vo.CourseOrderVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Ordering;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zongchangjiang
 * @since 2023-08-04
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {
    @Autowired
    private EsCourseOpenFeign esCourseOpenFeign;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private OrderProducer orderProducer;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private KillOpenFeign killOpenFeign;

    /**
     * 保存订单  和  订单明细
     * @param courseOrderVo
     * @return
     */
    @Override
    public JsonResult placeOrder(CourseOrderVo courseOrderVo,Long userId) {
        //生成订单号
        String orderSn = CodeGenerateUtils.generateOrderSn(userId);

        placeOrder(courseOrderVo, userId, orderSn);

        return JsonResult.success().setData(orderSn);
    }

    private void placeOrder(CourseOrderVo courseOrderVo, Long userId, String orderSn) {
        //保存订单
        CourseOrder courseOrder = new CourseOrder();
        courseOrder.setCreateTime(new Date());
        courseOrder.setOrderNo(orderSn);
        courseOrder.setUserId(userId);

        courseOrder.setTotalCount(courseOrderVo.getCourseIds().size());
        //订单状态：0下单成功待支付，1已支付，2订单取消，3订单退款，4支付超时或失败，5订单确认订单完成
        courseOrder.setStatusOrder(RConst.Num.INT_0);
        courseOrder.setPayType(courseOrderVo.getPayType());
        courseOrder.setOrderType(courseOrderVo.getType());

        //查询es
        List<Long> courseIds = courseOrderVo.getCourseIds();
        //使用流去查询 并且返回指定类型数据
        List<CourseDoc> collect = courseIds.stream().map(id -> {
            JsonResult jsonResult = esCourseOpenFeign.queryOne(id);
            String s = jsonResult.getData().toString();
            return JSON.parseObject(s, CourseDoc.class);
        }).collect(Collectors.toList());

        courseOrder.setCourseIds(courseIds);

        List<String> title = new ArrayList<>();
        Double totalAmount = new Double(RConst.Num.DOUBLE_0);
        Double payAmount = new Double(RConst.Num.DOUBLE_0);
        //存明细
        List<CourseOrderItem> items = new ArrayList<>();
        for (CourseDoc courseDoc : collect) {
            items.add(builderOrderItem(courseDoc, orderSn));//构建明细
            title.add(courseDoc.getName());
            if(courseOrderVo.getType().equals(RConst.Num.INT_1)) { //表示秒杀过来的
                JsonResult jsonResult = killOpenFeign.oneByOrder(courseDoc.getId());
                KillCourse killCourse = JSON.parseObject(jsonResult.getData().toString(), KillCourse.class);
                totalAmount += killCourse.getKillPrice().doubleValue();//todo
                payAmount +=killCourse.getKillPrice().doubleValue();//todo
            }else {
                totalAmount += courseDoc.getPriceOld();
                payAmount += courseDoc.getPrice();
            }
        }
        //要去查询课程才能计算出 总价
        courseOrder.setTotalAmount(new BigDecimal(totalAmount));
        courseOrder.setPayAmount(new BigDecimal(payAmount));
        courseOrder.setDiscountAmount(new BigDecimal(totalAmount - payAmount));
        courseOrder.setTitle(String.join(",",title));
        //todo  没有执行本地事务   让MQ的事务消息去执行本地事务
        //发送事务消息
        orderProducer.sendTransactionMessage(courseOrder,items);

        //发送站内信
        orderProducer.sendSystemMessage(courseOrder);
        //发送一个延迟消息  检查用户是否去支付了
        orderProducer.sendDelayMessage(courseOrder);
    }

    @Override
    public void save(CourseOrder courseOrder, List<CourseOrderItem> items) {
        baseMapper.insert(courseOrder);
        //保存订单明细
        //问题  没有 订单id
        items.forEach(item-> item.setOrderId(courseOrder.getId()));
        courseOrderItemService.saveBatch(items);
    }

    @Override
    public JsonResult killPlaceOrder(CourseOrderVo courseOrderVo, Long userId) {
        placeOrder(courseOrderVo,userId,courseOrderVo.getOrderNo());
        return JsonResult.success().setData(courseOrderVo.getOrderNo());
    }

    private CourseOrderItem builderOrderItem(CourseDoc courseDoc,String orderSn){
        CourseOrderItem courseOrderItem = new CourseOrderItem();
        courseOrderItem.setAmount(new BigDecimal(courseDoc.getPrice()));
        courseOrderItem.setPrice(new BigDecimal(courseDoc.getPriceOld()));
        courseOrderItem.setCount(RConst.Num.INT_1);
        courseOrderItem.setCourseId(courseDoc.getId());
        courseOrderItem.setCourseName(courseDoc.getName());
        courseOrderItem.setCoursePic(courseDoc.getPic());
        courseOrderItem.setOrderNo(orderSn);
        return courseOrderItem;
    }
}
